package com.java3_20;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket3 {
    private int ticket;

    public Ticket3() {

    }

    public Ticket3(int ticket) {
        this.ticket = ticket;
    }

    public int getTicket() {
        return ticket;
    }

    public void setTicket(int ticket) {
        this.ticket = ticket;
    }


    //使用Lock接口来限制线程
    Lock lock = new ReentrantLock();
    public void addTicket() {
        lock.lock();
            while (ticket < 5) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ticket++;
                System.out.println("当前的票数为：" + ticket);
                this.notifyAll();
            }
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        lock.unlock();
    }

    public void deleteTicket() {
        lock.lock();
            while(ticket>0){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ticket--;
                System.out.println("当前的票数为：" + ticket);
                this.notifyAll();
            }
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.unlock();
        }


}
